<script setup lang="ts">
import { reactive } from 'vue';
import { showLoading, showToast } from '@tarojs/taro';
import { Right as AppNutIconRight } from '@nutui/icons-vue-taro';
import { QUERY_FP_ASSET_REPAIR_TYPE_LIST } from '/@/api/modules/flow-path/flow-path-repair-type';
const props = defineProps<{
  placeholder: string;
  /**
   * 显示之前选过的值
   */
  selectedValue?: string;
  /**
   *
   */
  assetTypeId?: string;
}>();

const emits = defineEmits<{
  (e: 'onChange', repairTypeId: string, repairTypeName: string): void;
}>();
//局部
const state: {
  radioVal: string;
  radioPickerVisible: boolean;
  list: { text: string; value: string }[];
  /**
   * 资产类型id
   */
  assetTypeId?: string;
} = reactive({
  radioVal: '',
  radioPickerVisible: false,
  list: [],
});

//显示之前选过的值
if (props.selectedValue) {
  state.radioVal = props.selectedValue;
  state.assetTypeId = props.assetTypeId;
  state.assetTypeId && queryList(state.assetTypeId);
}
function confirm({ selectedOptions }) {
  state.radioVal = selectedOptions[0].text;
  state.radioPickerVisible = false;
  emits('onChange', selectedOptions[0].value, selectedOptions[0].text);
}

function selectRepairType() {
  if (!state.assetTypeId) {
    showToast({ title: '请先选择资产名称', icon: 'error' });
    return;
  }
  state.radioPickerVisible = !state.radioPickerVisible;
}
/**
 * 查询列表
 */
function queryList(assetTypeId: string) {
  showLoading();
  // 清空
  QUERY_FP_ASSET_REPAIR_TYPE_LIST({ assetTypeId: assetTypeId }).then((res) => {
    res.fpAssetRepairTypeDtoList?.forEach((item) => {
      item.repairTypeName &&
        item.id &&
        state.list.push({ text: item.repairTypeName, value: item.id });
    });
    state.list.push({ text: '其他', value: '-1' });
    selectFirstByDefault();
  });
}

function selectFirstByDefault() {
  const { text, value } = state.list[0];
  state.radioVal = text;
  emits('onChange', value, text);
}
</script>
<template>
  <view v-bind="$attrs" class="asset-type-picker" @click="selectRepairType()">
    <text>{{ state.radioVal || props.placeholder }}</text>
    <app-nut-icon-right />
  </view>
  <nut-popup position="bottom" v-model:visible="state.radioPickerVisible">
    <nut-picker
      :columns="state.list"
      :title="props.placeholder"
      @cancel="state.radioPickerVisible = false"
      @close="state.radioPickerVisible = false"
      @confirm="confirm"
    ></nut-picker>
  </nut-popup>
</template>
<style lang="scss">
.asset-type-picker {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>
